<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/*数字资源（中文在线）model*/

class ResourceQqrd extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_qqrd';



    /*关联活动类型*/
    public function conBigType()
    {
        return $this->hasOne(ResourceType::class, 'id', 'big_type_id');
    }


    /*关联活动类型*/
    public function conType()
    {
        return $this->hasOne(ResourceTypeExternal::class, 'id', 'type_id');
    }

    /**
     * 获取书籍详情
     * @param id  书籍id
     * @param guid  书籍guid  和 书籍id 2选一
     * @param resource_business_id  资源商id
     */
    public function detail($id = null, $guid = null)
    {
        if (empty($id) && empty($guid)) {
            return false;
        }
        $res = $this->select([
            'id',
            'guid',
            'resource_business_id',
            'title',
            'author',
            'isbn',
            'press',
            'pre_time',
            'img',
            'intro',
            'create_time',
            'big_type_id',
            'type_id',
            'browse_num',
            'is_recom'
            // 'h5_link',
            // 'web_link',
        ])->with('conBigType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->with('conType', function ($query) {
            $query->select('id', 'type_name')->where('is_del', 1);
        })->where(function ($query) use ($id, $guid) {
            if ($id) {
                $query->where('id', $id);
            } else {
                $query->where('guid', $guid);
            }
        })->where('is_del', 1)
            ->first();

        if ($res) {
            $is_exists_chapter = ResourceBusinessName::where('id', $res->resource_business_id)->value('is_exists_chapter');
            $res->is_exists_chapter = $is_exists_chapter == 1 ? true : false; //是否存在章节，有则可以获取
        }
        return $res;
    }


    /**
     * 添加数据到数据库
     * @param $data
     */
    public function addData($data)
    {
        if (empty($data['bid'])) {
            return false;
        }

        $categorys = !empty($data['categoryid']) ? trim($data['categoryid']) : ''; //数据多了一个分号
        $big_type_id = 1; //固定是电子书类型
        $type_id = null;
        if (!empty($categorys)) {
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $type_id = $resourceTypeExternalModel->getQqrdTypeIdByOriginalId(2, $categorys);
        }
        $res = $this->where('data_unique_id', $data['bid'])->first(); //bid 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($res)) {
            //修改
            $res = new self();
            $guid = get_guid();
            $res->guid = $guid;
        }
        //以下一段代码根据需求打开与关闭
        else if ($res->original_change_time == $data['updatetime']) {
            return true; //未修改过数据，不更新
        }

        //  else {
        //     Log::channel('escmdlog')->debug('遇到相同数据' . $data['shId']);
        //     Log::channel('escmdlog')->debug($data);
        //     Log::channel('escmdlog')->debug($res->toArray());
        //     die;
        // }
        $res->bid = $data['bid'];
        $res->resource_business_id = 2; //固定2,QQ阅读
        $res->title = $data['title']; //固定2,QQ阅读
        $res->big_type_id = $big_type_id;
        $res->type_id = $type_id;
        $res->img = $data['coverUrl'];
        $res->intro = $data['intro'];
        $res->author = $data['authorname'];
        $res->isbn = str_replace('-', '', $data['isbn']);
        $res->all_words = $data['allWords'];
        $res->category_id = $data['categoryid'];
        $res->original_create_time_old = $data['createTime'];
        $res->original_change_time_old = $data['updatetime'];
        $res->original_create_time = date('Y-m-d H:i:s', substr($data['createTime'], 0, 10));
        $res->original_change_time = date('Y-m-d H:i:s', substr($data['updatetime'], 0, 10));
        $res->format = $data['format'];
        $res->h5_link = !empty($data['h5']) ? $data['h5'] : '';
        $res->web_link = !empty($data['web']) ? $data['web'] : '';
        $res->press = null;
        $res->pre_time = null;
        $res->data_unique_id = $data['bid']; //数据唯一id
        $res->change_time = date('Y-m-d H:i:s'); //数据唯一id
        $res->is_del = 1;
        $res->save();

        //加入到资源总数据库
        $resourceTotalModel = new ResourceTotal();

        $resourceTotalModel->addData($res);

        return $res->id;
    }

    /**
     *删除下架数据
     */
    public function deleteData($bid)
    {
        $res = $this->where('bid', $bid)->where('is_del', 1)->first(); //bid 区分大小写检索     数据库对应，数据字段 设置为 binary 也可以
        if (empty($res)) {
            return true;
        }
        $res->is_del = 2;
        $res->save();

        //删除总数据
        $resourceTotalModel = new ResourceTotal();
        $resourceTotalModel->deleteData($res->guid);

        return true;
    }

    /**
     * 获取图书阅读跳转地址
     * @param guid  章节id
     */
    public function getResourceSkipAddress($guid)
    {
        $res = $this->select('h5_link', 'web_link', 'bid')->where('is_del', 1)->where('guid', $guid)->first();
        if (empty($res)) {
            return false;
        }
        return $res;
    }
}
